package com.rupertjones.globalcron.domain.dao;

import com.rupertjones.globalcron.domain.AuditLog;
import com.rupertjones.globalcron.domain.User;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static org.hibernate.criterion.Restrictions.eq;
import static org.hibernate.criterion.Restrictions.ne;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
@Repository
public class AuditLogDAO extends AbstractHibernateDAO<AuditLog> {
    public AuditLogDAO() {
        super(AuditLog.class);
    }

    @SuppressWarnings("unchecked")
    public List<AuditLog> findAllByUser(User user) {
        List<AuditLog> raw = getCriteria().add(eq("user", user.getUsername())).list();
        sort(raw);
        return raw;
    }

    @SuppressWarnings("unchecked")
    public List<AuditLog> findAllNotUser(User user) {
        List<AuditLog> raw = getCriteria().add(ne("user", user.getUsername())).list();
        sort(raw);
        return raw;
    }

    private void sort(List<AuditLog> input) {
        Collections.sort(input, new Comparator<AuditLog>() {
            @Override
            public int compare(AuditLog o1, AuditLog o2) {
                return o2.getCreatedAt().compareTo(o1.getCreatedAt());
            }
        });
    }
}
